package com.mobile.mobilehardware.utils;

import com.mobile.mobilehardware.base.BaseData;
import ohos.app.Context;
import ohos.net.NetCapabilities;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.telephony.RadioInfoManager;
import ohos.telephony.TelephonyConstants;
import ohos.wifi.WifiDevice;
import ohos.wifi.WifiUtils;

public class DataUtil {
    private static final String TAG = "DataUtil";

    /**
     * 拿到具体的网络类型
     *
     * @param context Application context
     * @return WIFI if connected to wifi, else cellular network type as 2G,3G,4G
     */
    public static String networkTypeALL(Context context) {
        NetManager manager = NetManager.getInstance(context);
        if (manager != null) {
            WifiDevice wifiDevice = WifiDevice.getInstance(context);
            if (wifiDevice != null && wifiDevice.isConnected()) {
                return "WIFI";
            }
        }

        RadioInfoManager radioInfoManager = RadioInfoManager.getInstance(context);
        if (radioInfoManager == null) {
            return "unknown";
        }
        int primarySlot = radioInfoManager.getPrimarySlotId();
        int networkType = radioInfoManager.getRadioTech(primarySlot);
        switch (networkType) {
            case TelephonyConstants.RADIO_TECHNOLOGY_GSM:
            case TelephonyConstants.RADIO_TECHNOLOGY_1XRTT:
                return "2G";
            case TelephonyConstants.RADIO_TECHNOLOGY_WCDMA:
            case TelephonyConstants.RADIO_TECHNOLOGY_HSPA:
            case TelephonyConstants.RADIO_TECHNOLOGY_HSPAP:
            case TelephonyConstants.RADIO_TECHNOLOGY_TD_SCDMA:
            case TelephonyConstants.RADIO_TECHNOLOGY_EVDO:
            case TelephonyConstants.RADIO_TECHNOLOGY_EHRPD:
                return "3G";
            case TelephonyConstants.RADIO_TECHNOLOGY_LTE:
            case TelephonyConstants.RADIO_TECHNOLOGY_LTE_CA:
                return "4G";
            case TelephonyConstants.RADIO_TECHNOLOGY_NR:
                return "5G";
            default:
                return BaseData.UNKNOWN_PARAM;

        }
    }

    /**
     * 网络是否可用
     * @param context COntext of application
     * @return True if network available, else false.
     */
    public static boolean isNetworkAvailable(Context context) {
        try {
            NetManager mgr = NetManager.getInstance(context);
            if (mgr == null) {
                return false;
            }
            NetHandle[] info = mgr.getAllNets();
            if (info != null) {
                for (NetHandle anInfo : info) {
                    NetCapabilities netCapabilities = mgr.getNetCapabilities(anInfo);
                    if (netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            return true;
        }
        return false;
    }

}
